package com.manchao.ssoserver.controller;

import com.sun.source.doctree.SeeTree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;


@Controller
public class LoginController {

    @Autowired
    StringRedisTemplate redisTemplate;

    @GetMapping("/login.html")
    public String doLogin(@RequestParam(value = "redirect_url") String url,
                          Model model,
                          @CookieValue(value = "sso_token",required = false) String sso_token){
        if (!StringUtils.isEmpty(sso_token)) {
            //之前有人登录了
            return "redirect:"+url+"?token="+sso_token;
        }
        model.addAttribute("url",url);
        return "login";
    }

    @PostMapping("/save")
    public String save(@RequestParam("username") String username,
                       @RequestParam("password") String password,
                       @RequestParam("url") String url,
                       HttpServletResponse response){

        String uuid = UUID.randomUUID().toString().replace("-","");
        redisTemplate.opsForValue().set(uuid,username);

        //把uuid作为cookie保存服务端sso.com域名
        Cookie cookie = new Cookie("sso_token",uuid);
        response.addCookie(cookie);

        return "redirect:"+url+"?token="+uuid;
    }
}
